package com.example.security.controller;

import com.example.security.dmo.SysUser;
import com.example.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/product")
public class ProductController {
    @GetMapping("/findAll")
    public String findAll(){
        return "返回所有列表";
    }

    @Autowired
    private UserMapper userMapper;


    @RequestMapping("/getsession")
    public String getSession(HttpServletRequest request){
        return request.getSession().toString();
    }

    @GetMapping("/getUser")
    public SysUser getUser(@RequestParam String username){
        return userMapper.getUserInfoByUsername(username);
    }

    @PreAuthorize("hasAnyRole('user')")
    @GetMapping("/user")
    public String user(){
        UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(principal.toString());
        return "user角色访问";
    }
    @PreAuthorize("hasAnyRole('admin')")
    @GetMapping("/admin")
    public String admin(){
        return "admin管理员访问";
    }

    @Autowired
    private PasswordEncoder passwordEncoder;
    @PreAuthorize("hasRole('admin')")
    @PostMapping("/addUser")
    public int addUser(@RequestBody SysUser user){
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userMapper.insertUser(user);
    }

    @PutMapping("/updateUser")
    public int updateUser(@RequestBody Map<String,String> map){
        // 获取当前登录用户信息(注意：没有密码的)
        UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = principal.getUsername();

        // 通过用户名获取到用户信息（获取密码）
        SysUser userInfo = userMapper.getUserInfoByUsername(username);

        // 判断输入的旧密码是正确
        if (passwordEncoder.matches(map.get("oldPwd"), userInfo.getPassword())) {
            // 不要忘记加密新密码
            return userMapper.updateUser(username, passwordEncoder.encode(map.get("newPwd")));
        }
        return 0;
    }
}
